package com.future.heatwave

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.future.heatwave.network.ApiServiceImp
import com.future.heatwave.ui.theme.HeatShortDataTheme
import com.future.heatwave.ui.theme.Pink80
import com.future.heatwave.viewmodel.AchieveDataViewModel
import com.future.heatwave.viewmodel.GainDataViewModel
import com.future.heatwave.viewmodel.ObtainDataViewModel
import com.future.heatwave.viewmodel.ParticleDataViewModel
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.jvm.internal.Intrinsics

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {


            HeatShortDataTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background
                ) {
                    val obtainDataViewModel = ObtainDataViewModel(application)
                    Greeting(this.application, obtainDataViewModel)
                }
            }
        }
    }
}

fun getAdvId(application: Application): String? {
    val advertisingIdInfo: AdvertisingIdClient.Info =
        AdvertisingIdClient.getAdvertisingIdInfo(application)
    Intrinsics.checkNotNullExpressionValue(
        advertisingIdInfo,
        "getAdvertisingIdInfo(applicationContext)"
    )
    var id: String? = advertisingIdInfo.getId()


    return id
}

fun shuffleUuid(uuid: String): String {
    val lengths = listOf(8, 4, 4, 4, 12)

    // 字符集合：数字和小写字母
    val chars = ('0'..'9') + ('a'..'f')

    // 用于存储结果的列表
    val parts = mutableListOf<String>()

    // 生成每个部分的随机字符串
    for (length in lengths) {
        val part = StringBuilder(length)
        repeat(length) {
            part.append(chars.random())
        }
        parts.add(part.toString())
    }

    // 用破折号连接各个部分
    return parts.joinToString("-")
}

@SuppressLint("CheckResult")
@Composable
fun Greeting(
    application: Application,
    obtainDataViewModel: ObtainDataViewModel,
    modifier: Modifier = Modifier
) {
    LaunchedEffect(Unit) {
        run {

            var advId = ("12bb64bb-b4c5-4db6-bbda-100ede986ada")
//            val shuffled = advId.toList().shuffled().joinToString("")
            val SignConfigParams = HashMap<String, String>()
            SignConfigParams["outlineType"] = System.currentTimeMillis().toString()
            val RegisterParams = HashMap<String, String>()
            RegisterParams["type"] = "0"
            RegisterParams["sysVersion"] = "13"
            RegisterParams["model"] = "samsung"
//            RegisterParams["advId"] = getAdvId(application).toString()
            RegisterParams["advId"] = advId
            RegisterParams["receiveType"] = "1"
            RegisterParams["userKey"] = "0"
            RegisterParams["channel"] = "utm_source=google-play"
            RegisterParams["utm_medium"] = "organic"
            val observable = ApiServiceImp.getAppraise().flatMap { response1 ->
                Log.e("bLog", " **response1  ${response1.piece}")
                ApiServiceImp.getConfigActivity().flatMap { response2 ->
                    Log.e("bLog", " **response2  ${response2.code}")
                    ApiServiceImp.getSignRecord().flatMap { response3 ->
                        Log.e("bLog", " **response3  ${response3.coding}")
                        ApiServiceImp.getUnAutoCoinsMsgs().flatMap { response4 ->
                            Log.e("bLog", " **response4  ${response4.qrCode}")
                            ApiServiceImp.getSignConfig(SignConfigParams).flatMap { response5 ->
                                Log.e("bLog", " **response5  ${response5.encode}")
                                ApiServiceImp.getRegister(RegisterParams)
                            }
                        }
                    }
                }
            }
            observable.subscribeOn(Schedulers.io()) // 在 IO 线程上执行请求
                .observeOn(AndroidSchedulers.mainThread()) // 在主线程上观察结果
                .subscribe({ response ->
                    Log.e(
                        "bLog",
                        " **response  ${response}*******"
                    )

                }) { throwable ->
                    Log.e(
                        "bLog",
                        " **throwable  ${throwable.message}"
                    )
                }

        }
    }
    val achieveDataViewModel = AchieveDataViewModel(application)

    Column(modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally) {


//        val queryParams = HashMap<String, String>()
//        queryParams["Accept-Encoding"] ="gzip"
//        queryParams["appInfo"] = "73c74a1a-3bf7-3074-a05a-3da2414a21ea&com.future.heatwave&V2.2.7"
//        queryParams["Authorization"] = "6044EABAC9380BD8D99A76CE5B024519"
//        queryParams["Connection"] = "Keep-Alive"
//        queryParams["Host"] = "api.heatshort.com"
//        queryParams["signCode"] = "10000"
//        queryParams["timestamp"] = "1713758354738"
//        queryParams["User-Agent"] = "okhttp/4.11.0"
//        val call: Call<String> =   ApiServiceImp.getAchieve()
//        call.enqueue(object : Callback<String?> {
//            override fun onResponse(call: Call<String?>?, response: Response<String?>) {
//                if (response.isSuccessful() && response.body() != null) {
//                    try {
//                        // 获取完整的 JSON 字符串
//                        val jsonString: String = response.body()!!
//                        Log.d("JSON Response", jsonString)
//
//                        // 在这里你可以将 jsonString 传递给 JSON 解析器来解析数据
//                    } catch (e: IOException) {
//                        e.printStackTrace()
//                    }
//                } else {
//                    Log.e("Network Error", "Network request failed")
//                }
//            }
//
////            override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {
////                Log.e("Network Error", "Network request failed: " + t.message)
////            }
//
//            override fun onFailure(call: Call<String?>, t: Throwable) {
//                TODO("Not yet implemented")
//            }
//        })
        val timestamp = remember {
            System.currentTimeMillis()
        }
        val content = LocalContext.current as MainActivity
        /**
         * Achieve
         * 首页分类 table
         */
        Box(
            modifier = Modifier
                .padding(start = 30.dp, end = 30.dp)
                .fillMaxWidth()
                .padding(top = 15.dp)
                .clip(RoundedCornerShape(10.dp))
                .background(color = Pink80)
                .clickable {
                    ApiServiceImp
                        .getAchieve()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe({ achieve ->
                            Log.e(
                                "bLog",
                                "列表分类 code**：  ${achieve.qrCode}， ${achieve.information}"
                            )
                            achieve.metadata?.forEach { item ->
                                run {
                                    Log.e("bLog", "列表分类 **：  ${item.breakdownName}")
                                    achieveDataViewModel.insertItem(item)
                                }
                            }

                        }, {
                            Log.e("bLog", "列表分类 code  ${it.message}")
                        })

                    Toast
                        .makeText(content, "Go Go Go", Toast.LENGTH_SHORT)
                        .show()
                }, contentAlignment = Alignment.Center
        ) {
            Text(
                modifier = Modifier
                    .wrapContentSize()
                    .padding(15.dp),
                text = "列表分类",
                fontWeight = FontWeight.Bold,
                fontSize = 24.sp,
                textAlign = TextAlign.Center
            )
        }


        /**
         * Gain
         * 首页轮播
         */
        val gainDataViewModel = GainDataViewModel(application)
        Box(
            modifier = Modifier
                .padding(start = 30.dp, end = 30.dp)
                .fillMaxWidth()
                .padding(top = 15.dp)
                .clip(RoundedCornerShape(10.dp))
                .background(color = Pink80)
                .clickable {
                    ApiServiceImp
                        .getGain()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe({ gain ->
                            Log.e("bLog", "首页轮播数据 code**：  ${gain.coding},  ${gain.tiding}")
                            gain.data?.forEach { item ->
                                run {
                                    Log.e("bLog", "首页轮播数据 **：  ${item.technique}")
                                    gainDataViewModel.insertItem(item)
                                }
                            }

                        }, {
                            Log.e("bLog", "请求首页信息时报 code  ${it.message}")
                        })

                    Toast
                        .makeText(content, "Go Go Go", Toast.LENGTH_SHORT)
                        .show()
                }, contentAlignment = Alignment.Center
        ) {
            Text(
                modifier = Modifier
                    .wrapContentSize()
                    .padding(15.dp),
                text = "首页轮播数据",
                fontWeight = FontWeight.Bold,
                fontSize = 24.sp,
                textAlign = TextAlign.Center
            )
        }


        /**
         * Obtain
         * Most Popular列表
         */

        val obtainIds = remember {
            mutableStateListOf<Long>()
        }
        Box(
            modifier = Modifier
                .padding(start = 30.dp, end = 30.dp)
                .fillMaxWidth()
                .padding(top = 15.dp)
                .clip(RoundedCornerShape(10.dp))
                .background(color = Pink80)
                .clickable {
                    ApiServiceImp
                        .getObtainList()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe({ obtain ->
                            Log.e("bLog", "所有短剧列表 code**：  ${obtain.code},  ${obtain.intel}")
                            obtain.records?.forEach { item ->
                                run {
                                    Log.e("bLog", "所有短剧列表 **：  ${item.dramaName}")
                                    obtainIds.add(item.id)
                                    obtainDataViewModel.insertItem(item)
                                }
                            }

                        }, {
                            Log.e("bLog", "请求首页信息时报 code  ${it.message}")
                        })

                    Toast
                        .makeText(content, "Go Go Go", Toast.LENGTH_SHORT)
                        .show()
                }, contentAlignment = Alignment.Center
        ) {
            Text(
                modifier = Modifier
                    .wrapContentSize()
                    .padding(15.dp),
                text = "请求首页信息时报",
                fontWeight = FontWeight.Bold,
                fontSize = 24.sp,
                textAlign = TextAlign.Center
            )
        }
        if (obtainIds.size == 0) {
            LaunchedEffect(Unit) {
                val obtains = obtainDataViewModel.getAllItems()
                obtains.forEach { item ->
                    obtainIds.add(item.id)
                }
            }
        }

        /**
         * Partic
         * 点击播放展示的视频信息
         */


        val particleDataViewModel = ParticleDataViewModel(application)

        val queryParams = HashMap<String, String>()
        if (obtainIds.size > 0) queryParams["operaId"] = obtainIds[0].toString()
        Box(
            modifier = Modifier
                .padding(start = 30.dp, end = 30.dp)
                .fillMaxWidth()
                .padding(top = 15.dp)
                .clip(RoundedCornerShape(10.dp))
                .background(color = Pink80)
                .clickable {
                    ApiServiceImp
                        .getPartic(queryParams)
                        ?.subscribeOn(Schedulers.io())
                        ?.observeOn(AndroidSchedulers.mainThread())
                        ?.subscribe({ obtain ->
                            Log.e("bLog", "点击播放是现实的信息**Scode  ${obtain.coding}")
                            obtain.datum?.let { particleDataViewModel.insertItem(it) }

                        }, {
                            Log.e("bLog", "请求首页信息时报 code  ${it.message}")
                        })

                    Toast
                        .makeText(content, "Go Go Go", Toast.LENGTH_SHORT)
                        .show()
                }, contentAlignment = Alignment.Center
        ) {
            Text(
                modifier = Modifier
                    .wrapContentSize()
                    .padding(15.dp),
                text = "点击播放时的信息",
                fontWeight = FontWeight.Bold,
                fontSize = 24.sp,
                textAlign = TextAlign.Center
            )
        }

        /**
         * 获取章节列表
         */

        val zjIds = remember {
            mutableStateListOf<Long>()
        }
        val dramaldIds = remember {
            mutableStateListOf<Long>()
        }
        val isImplement = remember {
            mutableStateOf(0)
        }
        val sectionsDataViewModel = SectionsDataViewModel(application)

        if (isImplement.value == 1) {
            LaunchedEffect(Unit) {
                var nextIndex = 0;
                obtainIds.forEachIndexed { index, obtainItemId ->
                    nextIndex = index
                    launch {
//                        Log.e("bLog", " **Scode   ${obtainItemId}")
                        delay((1..3).random() * 1000L) // 阻塞 1 到 3 秒


                        val querySectionsRecordParams = HashMap<String, String>()
                        querySectionsRecordParams["fictionId"] = obtainItemId.toString()
                        querySectionsRecordParams["useLinking"] = "true"
                        querySectionsRecordParams["languageCode"] = "US"
                        querySectionsRecordParams["isVpn"] = "0"
                        ApiServiceImp.getSections(querySectionsRecordParams)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())?.subscribe({ obtain ->
                                Log.e(
                                    "bLog",
                                    "获取每一部剧的所有章节信息 code**：  ${obtain.plait},,  ${obtain.msg}"
                                )
                                obtain.records.forEach { item ->
//                                    dramaldIds.add(item.dramaId)
//                                    zjIds.add(item.episodeNum)
                                    Log.e(
                                        "bLog",
                                        "获取每一部剧的所有章节信息 **短剧 id:${obtainItemId}, 章节id:${item.episodeNum}"
                                    )
                                    run { sectionsDataViewModel.insertItem(item) }
                                }

                            }, {
                                Log.e("bLog", "获取每一部剧的章节信息code  ${it.message}")
                            })

                        Toast.makeText(content, "Go Go Go", Toast.LENGTH_SHORT).show()
                    }

                }

            }

        }
        Box(
            modifier = Modifier
                .padding(start = 30.dp, end = 30.dp)
                .fillMaxWidth()
                .padding(top = 15.dp)
                .clip(RoundedCornerShape(10.dp))
                .background(color = Pink80)
                .clickable {
                    isImplement.value = 1

                }, contentAlignment = Alignment.Center
        ) {
            Text(
                modifier = Modifier
                    .wrapContentSize()
                    .padding(15.dp),
                text = "获取每一部剧的所有章节信息",
                fontWeight = FontWeight.Bold,
                fontSize = 24.sp,
                textAlign = TextAlign.Center
            )
        }

        /**
         * 获取免费章节播放信息
         */

        Box(
            modifier = Modifier
                .padding(start = 30.dp, end = 30.dp)
                .fillMaxWidth()
                .padding(top = 15.dp)
                .clip(RoundedCornerShape(10.dp))
                .background(color = Pink80)
                .clickable {

                    obtainIds.forEach { itemId ->
                        getFree(itemId.toString(), application, content)
                    }

                }, contentAlignment = Alignment.Center
        ) {
            Text(
                modifier = Modifier
                    .wrapContentSize()
                    .padding(15.dp),
                text = "获取每一部剧的免费视频",
                fontWeight = FontWeight.Bold,
                fontSize = 24.sp,
                textAlign = TextAlign.Center
            )
        }

        /**
         * 解锁
         */

//        if (zjIds.size == 0) {
//            LaunchedEffect(Unit) {
//                val sections = sectionsDataViewModel.getDramaIdAllSections()
//                sections.forEach { item ->
//                    zjIds.add(item.episodeNum)
//                }
//            }
//        }
        if (dramaldIds.size == 0) {
            LaunchedEffect(Unit) {
                val sections = sectionsDataViewModel.getAllItems()
                sections.forEach { item ->
                    dramaldIds.add(item.dramaId)
                }
            }
        }
        val isLock = remember {
            mutableStateOf(0)
        }
        if (isLock.value == 1) {
            LaunchedEffect(Unit) {
//                if (dramaldIds.size > 0) {
//                    dramaldIds.forEach { id ->
//                        delay((1..3).random() * 1000L) // 阻塞 1 到 3 秒
//                        val sections = sectionsDataViewModel.getDramaIdAllSections(dramaldIds[0])
                val sections =
                    sectionsDataViewModel.getDramaIdAllSections("1784777305205817346".toLong())
                zjIds.clear()
                sections.forEach { item ->
                    zjIds.add(item.episodeNum)
                }
                isLock.value = lockVideo(
//                            dramaldIds[0].toString(),
                    "1784777305205817346", content, application, 1784782676393771009
                )
//                    }
//                }
            }
        }
        Box(
            modifier = Modifier
                .padding(start = 30.dp, end = 30.dp)
                .fillMaxWidth()
                .padding(top = 15.dp)
                .clip(RoundedCornerShape(10.dp))
                .background(color = Pink80)
                .clickable {
                    isLock.value = 1
                }, contentAlignment = Alignment.Center
        ) {
            Text(
                modifier = Modifier
                    .wrapContentSize()
                    .padding(15.dp),
                text = "看广告解锁所有付费视频",
                fontWeight = FontWeight.Bold,
                fontSize = 24.sp,
                textAlign = TextAlign.Center
            )
        }
    }


//        SimpleProgressBar(progress = 0.5f)

}

/**
 * 获取免费
 */
@SuppressLint("CheckResult")
fun getFree(id: String, application: Application, content: Context) {
    val sectionsInfoDataViewModel = SectionsInfoDataViewModel(application)
    val querySectionsInfoParams = HashMap<String, String>()
    querySectionsInfoParams["shortPlayId"] = id
    querySectionsInfoParams["pageNum"] = "1"
    querySectionsInfoParams["leafSize"] = "100"
    querySectionsInfoParams["lingoEncrypt"] = "US"
    querySectionsInfoParams["isAgent"] = "0"
    querySectionsInfoParams["useUrl"] = "true"
    ApiServiceImp.getFreeSectionsInfo(querySectionsInfoParams).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread()).subscribe({ obtain ->
            Log.e("bLog", "获取每一部剧的免费章节 Size：${obtain.records.size}")
            obtain.records.forEach { item ->
                run { sectionsInfoDataViewModel.insertItem(item) }
            }

        }, {
            Log.e("bLog", "请求首页信息时报 code  ${it.message}")
        })

    Toast.makeText(content, "Go Go Go", Toast.LENGTH_SHORT).show()
}

/**
 * 解锁后  更新免费视频库
 */
@SuppressLint("CheckResult")
fun getFreeOrLock(id: String, application: Application, content: Context) {
    val sectionsInfoDataViewModel = SectionsInfoDataViewModel(application)
    val querySectionsInfoParams = HashMap<String, String>()
    querySectionsInfoParams["shortPlayId"] = id
    querySectionsInfoParams["pageNum"] = "1"
    querySectionsInfoParams["leafSize"] = "100"
    querySectionsInfoParams["lingoEncrypt"] = "US"
    querySectionsInfoParams["isAGent"] = "0"
    querySectionsInfoParams["useUrl"] = "true"
    ApiServiceImp
//        .adsConfig()
        .getFreeSectionsInfo(querySectionsInfoParams).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
//        .flatMap { response1 ->
//            Log.e("bLog", "解锁后 **response1  ${response1.plait}")
//            ApiServiceImp.getFreeSectionsInfo(querySectionsInfoParams)!!
//        }
        .subscribe({ obtain ->
            Log.e("bLog", "解锁后  更新免费视频库 **response2  ${obtain.encipher}")
            obtain.records.forEach { item ->
                run { sectionsInfoDataViewModel.insertItem(item) }
            }

        }, {
            Log.e("bLog", "解锁后  更新免费视频库 code  ${it.message}")
        })


}

fun shuffleString(input: String): String {
    // 将字符串转换为字符数组
    val charArray = input.toCharArray()

    // 打乱字符数组的顺序
    charArray.shuffle()

    // 将字符数组转换回字符串
    return String(charArray)
}

fun isMultipleOfTenOrNine(number: Int): Boolean {
    return number % 10 == 0 || number % 9 == 0
}

val deviceModels = listOf(
    "Pixel 6 Pro",
    "Samsung Galaxy S21 Ultra",
    "OnePlus 9 Pro",
    "Xiaomi Mi 11",
    "Google Pixel 5",
    "Samsung Galaxy Note 20 Ultra",
    "OnePlus 8T",
    "Xiaomi Mi 10 Pro",
    "Google Pixel 4a",
    "Samsung Galaxy S20",
    "OnePlus 7T Pro",
    "Xiaomi Mi Note 10",
    "Google Pixel 3a",
    "Samsung Galaxy A52",
    "OnePlus Nord",
    "Xiaomi Redmi Note 9 Pro",
    "Google Pixel 2 XL",
    "Samsung Galaxy A72",
    "OnePlus 6T",
    "Xiaomi Redmi Note 8"
)

// 从列表中随机选择一个不重复的型号
fun getRandomDeviceModel(): String {
    return deviceModels.shuffled().first()
}

/**
 * 解锁视频
 */
@SuppressLint("CheckResult")
fun lockVideo(fid: String, content: Context, application: Application, list: Long): Int {
    Log.e("bLog", "************************************* **fid  ${fid}***${list}")
    var backState = 0
//    list.forEachIndexed { index, id ->
//        if(index >9)
//            return 0
//        Thread.sleep(TimeUnit.SECONDS.toMillis(1))
//        backState = index
    var deviceId = "250cb7fc5a334330884f02a73c7fb5ca6"
    var facilityType = "SM-A5160"
//        if (isMultipleOfTenOrNine(backState)) {
//            deviceId = shuffleString("250cb7fc5a334330884f02a73c7fb5ca6")
//            facilityType = getRandomDeviceModel()
//            val RegisterParams = HashMap<String, String>()
//            val model = when (deviceId) {
//                "Pixel 6 Pro" -> {
//                    "pixel"
//                }
//
//                "Samsung Galaxy S21 Ultra" -> {
//                    "samsung"
//                }
//
//                "OnePlus 9 Pro" -> {
//                    "oneplus"
//                }
//
//                "Xiaomi Mi 11" -> {
//                    "xiaomi"
//                }
//
//                "Google Pixel 5" -> {
//                    "google pixel"
//                }
//
//                "Samsung Galaxy Note 20 Ultra" -> {
//                    "samsung"
//                }
//
//                "OnePlus 8T" -> {
//                    "oneplus"
//                }
//
//                "Xiaomi Mi 10 Pro" -> {
//                    "xiaomi"
//                }
//
//                "Google Pixel 4a" -> {
//                    "google pixel"
//                }
//
//                "Samsung Galaxy S20" -> {
//                    "samsung"
//                }
//
//                "OnePlus 7T Pro" -> {
//                    "oneplus"
//                }
//
//                "Xiaomi Mi Note 10" -> {
//                    "xiaomi"
//                }
//
//                "Google Pixel 3a" -> {
//                    "google pixel"
//                }
//
//                "Samsung Galaxy A52" -> {
//                    "samsung"
//                }
//
//                "OnePlus Nord" -> {
//                    "oneplus"
//                }
//
//                "Xiaomi Redmi Note 9 Pro" -> {
//                    "google pixel"
//                }
//
//                "Google Pixel 2 XL" -> {
//                    "google pixel"
//                }
//
//                "Samsung Galaxy A72" -> {
//                    "samsung"
//                }
//
//                "OnePlus 6T" -> {
//                    "oneplus"
//                }
//
//                "Xiaomi Redmi Note 8" -> {
//                    "xiaomi"
//                }
//
//                else -> {
//                    "samsung"
//                }
//            }
//            RegisterParams["type"] = "0"
//            RegisterParams["sysVersion"] = "13"
//            RegisterParams["model"] = model
//            var advId = shuffleUuid("12bb64bb-b4c5-4db6-bbda-100ede986ada")
//            RegisterParams["advId"] = advId
//            RegisterParams["receiveType"] = "1"
//            RegisterParams["userKey"] = "0"
//            RegisterParams["channel"] = "utm_source=google-play"
//            RegisterParams["utm_medium"] = "organic"
//            val observable = ApiServiceImp.getRegister(RegisterParams)
//            observable.subscribeOn(Schedulers.io()) // 在 IO 线程上执行请求
//                .observeOn(AndroidSchedulers.mainThread()) // 在主线程上观察结果
//                .subscribe({ response ->
//                    Log.e(
//                        "bLog",
//                        "Register注册登记设备信息 **response  ${response}*******"
//                    )
//
//                }) { throwable ->
//                    Log.e(
//                        "bLog",
//                        " **throwable  ${throwable.message}"
//                    )
//                }
//        }
    val DotServerParams = HashMap<String, String>()
    DotServerParams["incidentName"] = "start_number"
    DotServerParams["deviceId"] = deviceId
    DotServerParams["facilityType"] = facilityType
    DotServerParams["videoId"] = fid
    DotServerParams["episodeId"] = list.toString()
    DotServerParams["userRegion"] = "TW"
    DotServerParams["putOnHours"] = ""
    DotServerParams["userRegion"] = ""
    val DotServerParamsNext = HashMap<String, String>()
    DotServerParamsNext["incidentName"] = "start_number"
    DotServerParamsNext["deviceId"] = deviceId
    DotServerParamsNext["facilityType"] = facilityType
    DotServerParamsNext["videoId"] = fid
    DotServerParamsNext["episodeId"] = (list + 1).toString()
    DotServerParamsNext["userRegion"] = "TW"
    DotServerParamsNext["putOnHours"] = ""
    val DotServerParams1 = HashMap<String, String>()
    DotServerParams1["incidentName"] = "advertising_release"
    DotServerParams1["deviceId"] = deviceId
    DotServerParams1["facilityType"] = facilityType
    DotServerParams1["videoId"] = fid
    DotServerParams1["putOnHours"] = ""
    DotServerParams1["episodeId"] = list.toString()
    DotServerParams1["userRegion"] = "TW"
    val DotServerParams2 = HashMap<String, String>()
    DotServerParams2["incidentName"] = "ad_impression"
    DotServerParams2["deviceId"] = deviceId
    DotServerParams2["facilityType"] = facilityType
    DotServerParams2["userRegion"] = "TW"
    DotServerParams2["putOnHours"] = ""
    val DotServerParams3 = HashMap<String, String>()
    DotServerParams3["incidentName"] = "start_play_number"
    DotServerParams3["deviceId"] = deviceId
    DotServerParams3["facilityType"] = facilityType
    DotServerParams3["videoId"] = fid
    DotServerParams3["episodeId"] = list.toString()
    DotServerParams3["userRegion"] = "TW"
    DotServerParams3["putOnHours"] = ""

    val AdRecordParams = HashMap<String, String>()
    val adverId = (System.currentTimeMillis() + 150000).toString()
    AdRecordParams["prizeType"] = "1"
    AdRecordParams["advertId"] = adverId
//        AdRecordParams["advertId"] = "1714374129527"
    AdRecordParams["videoId"] = list.toString()
    AdRecordParams["dramaSeriesId"] = fid

    val SkimParams = HashMap<String, String>()
    SkimParams["dramaId"] = fid
    SkimParams["episodeId"] = list.toString()


    val SectionsParams = HashMap<String, String>()
    SectionsParams["fictionId"] = fid
    SectionsParams["useLinking"] = "true"
    SectionsParams["languageCode"] = "US"
    SectionsParams["isVpn"] = "0"
    val sectionsInfoDataViewModel = SectionsInfoDataViewModel(application)
    val querySectionsInfoParams = HashMap<String, String>()
    querySectionsInfoParams["shortPlayId"] = fid
    querySectionsInfoParams["pageNum"] = "1"
    querySectionsInfoParams["leafSize"] = "100"
    querySectionsInfoParams["lingoEncrypt"] = "US"
    querySectionsInfoParams["isAgent"] = "0"
    querySectionsInfoParams["useUrl"] = "true"
    val observable = ApiServiceImp.dotServerStart(DotServerParams).flatMap { response1 ->
        Log.e("bLog", "解锁 **response1  ${response1.code}")
        ApiServiceImp.dotServer(DotServerParams1).flatMap { response2 ->
            Log.e("bLog", "解锁 **response2  ${response2.code}")
            ApiServiceImp.dotServer(DotServerParams2).flatMap { response3 ->
                Log.e("bLog", "解锁 **response3  ${response3.code}")
                ApiServiceImp.dotServer(DotServerParams3).flatMap { response4 ->
                    Log.e("bLog", "解锁 **response4  ${response4.code}")
                    ApiServiceImp.dotServer(DotServerParamsNext).flatMap { responseNext ->
                        Log.e("bLog", "解锁 **responseNext  ${responseNext.code}")
                        ApiServiceImp.postAdRecord(AdRecordParams).flatMap { response5 ->
                            Log.e("bLog", "解锁 **response5  ${response5.encode}")
                            ApiServiceImp.getSkim(SkimParams).flatMap { response6 ->
                                Log.e("bLog", "解锁 **response6  ${response6.plait}")
                                ApiServiceImp.adsConfig().flatMap { response7 ->
                                    Log.e("bLog", "解锁 **response7  ${response7.weave}")
                                    ApiServiceImp.getSections(SectionsParams).flatMap { re8 ->
                                            Log.e("bLog", "解锁 **re8  ${re8.plait}")
                                            ApiServiceImp.getFreeSectionsInfo2(querySectionsInfoParams)
                                        }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    observable.subscribeOn(Schedulers.io()) // 在 IO 线程上执行请求
        .observeOn(AndroidSchedulers.mainThread()) // 在主线程上观察结果
        .subscribe({ response ->
            response.records.forEach { item ->
                Log.e(
                    "bLog",
                    "解锁 *获取每一部剧的所有免费章节信息 **:${item.episodes}"
                )
                run { sectionsInfoDataViewModel.insertItem(item) }
            }
//                response.records.forEach { item ->
//                    Log.e(
//                        "bLog",
//                        "解锁 *获取每一部剧的所有章节信息 **短剧 id:${item.dramaId}, 章节id:${item.episodeNum}，url:${item.plateUrl}"
//                    )
//                    run {
//                        val sectionsDataViewModel = SectionsDataViewModel(application)
//                        sectionsDataViewModel.insertItem(item)
//                    }
//                }
        }) { throwable ->
            Log.e(
                "bLog",
                "解锁 **throwable  ${throwable.message}"
            )
        }
//    }

//    if (backState == list.size - 1) {
//        backState = 0
//        getFreeOrLock(fid, application, content)
//    }

    return backState
}


@Composable
fun SimpleProgressBar(progress: Float) {
    Box(
        modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center
    ) {
        CircularProgressIndicator(
            modifier = Modifier.size(50.dp), color = Color.Blue, // 设置颜色
            strokeWidth = 4.dp // 设置圆圈的宽度
        )
    }
}


@Composable
fun GreetingPreview() {
    HeatShortDataTheme {

    }
}